<?php
/**
 * Created by 管理员类.
 * User: 尚金殿
 * Date: 2018/8/26
 * Time: 12:08
 */

namespace app\admin\controller;


use think\Db;

class AdminController extends CommonController
{
    protected $mysql = 'admin';
    protected $pk = 'admin_id';
    protected $name = 'username';
    protected $status = 'admin_status';


    //添加管理员
    public function add(){
        if($this->request->isPost()){
            //获取提交的数据
            $data = $this->request->param();

            //判定数据
            if(!$data['username']){
                return show(0,'用户名不能为空');
            }
            if(!$data['password']){
                return show(0,'密码不能为空');
            }
            if(!$data['group_id'] || !is_numeric($data['group_id'])){
                return show(0,'角色不能为空');
            }

            //判断有没有主键
            if(!empty($data['admin_id'])){
                $this->save($data);
            }

            //加密密码   拼接数据
            $data['password'] = getMD5Password($data['password']);
            $adminId = $this->getAdd($data);

            if(!$adminId){
                return show(0,'新增失败');
            }
                return show(1,'新增成功');

        }else{
            //获取角色表
            $group = Db::name('group')->where('group_status',1)->where('group_id != 1')->select();

            //变量输出
            $this->assign('group',$group);

            //加载模版
            return $this->fetch();
        }
    }


    //编辑管理员
    public function edit(){
        //获取ID
        $id = $this->request->param('id');

        //获取管理员数据
        $admin = Db::name($this->mysql)->where($this->pk,$id)->find();

        //获取角色
        $group = Db::name('group')->where('group_id != 1')->where('group_status',1)->select();

        //变量输出
        $this->assign(['admin'=>$admin,'group'=>$group]);

        //加载模版
        return $this->fetch();
    }

    //保存编辑操作
    public function save($data){
        //判定传递的数据
        if(!$data || !is_array($data)){
            return show(0,'传递的数据不合法');
        }
        //获取ID
        $id = $data['admin_id'];
        unset($data['admin_id']);

        //判定密码是否相同
        if($data['new_password'] != $data['password']){
            $data['password'] = getMD5Password($data['new_password']);
        }
        $data['update_time'] = time();
        //删除
        unset($data['new_password']);

        //入库
        $res = Db::name($this->mysql)->where($this->pk,$id)->update($data);

        if(!$res){
            return show(0,'更新失败');
        }
            return show(1,'更新成功');
    }
}